package inits

import (
	"github.com/spf13/viper"
	"go_pure_admin_api/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// 控制台打印sql语句日志
var newLogger = logger.New(
	log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
	logger.Config{
		SlowThreshold:             time.Second, // Slow SQL threshold
		LogLevel:                  logger.Info, // Log level
		IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
		ParameterizedQueries:      true,        // Don't include params in the SQL log
		Colorful:                  true,        // Disable color
	},
)

func MysqlInit() {
	dsn := viper.GetString("mysql.dsn")
	MysqlDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		global.Logger.Panic("数据库连接失败", err)
	}
	// 把数据库注册到全局变量
	global.DB = MysqlDB
	global.Logger.Info("Mysql数据库连接成功")
}
